from app.core.responses import Response
from modules.admin.models.OrderUsed import OrderUsed
from modules.admin.models.Orders import Orders
from schemas.order_used import Create, Update


class OrderUsedService:
    @staticmethod
    def create(form: Create):
        # 获取订单信息
        order = (Orders
                 .with_('order_item')
                 .with_count('order_used', lambda q: (q.where('status', '!=', 'cancelled')))
                 .order_paid(form.uid)
                 .where('id', form.order_id)
                 .first())
        if not order:
            return Response.failed('订单不存在')
        # 订单使用次数
        order_used_count = order.order_used_count
        # 订单购买次数
        order_quantity = order.order_item.quantity
        # 判断是否已使用完
        if order_used_count >= order_quantity:
            return Response.failed('订单已使用完')
        data = {
            'order_id': form.order_id,
            'uid': form.uid,
            'order_item_id': order.order_item.id,
            'status': form.status
        }
        OrderUsed.create(data)
        return Response.message('下单成功')


@staticmethod
def get_all(current, size):
    data = OrderUsed.paginate(size, current)
    return data


@staticmethod
def get_one(Id: int):
    data = OrderUsed.find(Id)
    return data


@staticmethod
def get_with_by_name(name: str):
    data = (OrderUsed.with_({'ad_items': lambda q: q.where("status", 'active').order_by('order', 'desc')})
            .where('name', name)
            .where('status', 'active')
            .first())
    return data


@staticmethod
def update(form: Update, ad_id: str):
    data = OrderUsed.find(ad_id)
    data.update(form.model_dump())
    return data


@staticmethod
def delete(Id):
    data = OrderUsed.find(Id)
    data.delete()
    return data
